
/*
 * Copyright 2002-2023 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*
 *版权所有2002-2023原作者。
 *
 *根据Apache许可证2.0版（“许可证”）获得许可；
 *除非符合许可证，否则不得使用此文件。
 *您可以在以下地址获取许可证副本：
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 *除非适用法律要求或书面同意，软件
 *根据许可证分发的内容是按“原样”分发的，
 *无任何明示或暗示的保证或条件。
 *有关管理权限和
 *许可证下的限制。
 */

package org.springframework.aop.interceptor;

import java.lang.reflect.Method;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.core.BridgeMethodResolver;
import org.springframework.core.Ordered;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.lang.Nullable;
import org.springframework.util.ClassUtils;

/**
 * AOP Alliance {@code MethodInterceptor} that processes method invocations
 * asynchronously, using a given {@link org.springframework.core.task.AsyncTaskExecutor}.
 * Typically used with the {@link org.springframework.scheduling.annotation.Async} annotation.
 *
 * <p>In terms of target method signatures, any parameter types are supported.
 * However, the return type is constrained to either {@code void} or
 * {@code java.util.concurrent.Future}. In the latter case, the Future handle
 * returned from the proxy will be an actual asynchronous Future that can be used
 * to track the result of the asynchronous method execution. However, since the
 * target method needs to implement the same signature, it will have to return
 * a temporary Future handle that just passes the return value through
 * (like Spring's {@link org.springframework.scheduling.annotation.AsyncResult}
 * or EJB's {@code jakarta.ejb.AsyncResult}).
 *
 * <p>When the return type is {@code java.util.concurrent.Future}, any exception thrown
 * during the execution can be accessed and managed by the caller. With {@code void}
 * return type however, such exceptions cannot be transmitted back. In that case an
 * {@link AsyncUncaughtExceptionHandler} can be registered to process such exceptions.
 *
 * <p>Note: the {@code AnnotationAsyncExecutionInterceptor} subclass is preferred
 * due to its support for executor qualification in conjunction with Spring's
 * {@code @Async} annotation.
 *
 * @author Juergen Hoeller
 * @author Chris Beams
 * @author Stephane Nicoll
 * @since 3.0
 * @see org.springframework.scheduling.annotation.Async
 * @see org.springframework.scheduling.annotation.AsyncAnnotationAdvisor
 * @see org.springframework.scheduling.annotation.AnnotationAsyncExecutionInterceptor
 */
/**
 *处理方法调用的AOP Alliance｛@code MethodInterceptor｝
 *使用给定的｛@link org.springframework.core.task.AsyncTaskExecutor｝异步执行。
 *通常与｛@link.org.springframework.schedung.annotation.Async｝注释一起使用。
 *
 *＜p＞就目标方法签名而言，支持任何参数类型。
 *但是，返回类型被限制为｛@code void｝或
 *｛@codejava.util.concurrent.Foure｝。在后一种情况下，Future句柄
 *从代理返回的将是可以使用的实际异步Future
 *以跟踪异步方法执行的结果。然而，自从
 *目标方法需要实现相同的签名，它必须返回
 *一个临时Future句柄，它只通过
 *（如Spring的{@link.org.springframework.schedung.annotation.AsyncResult}
 *或EJB的{@code jakarta.EJB.AncResult}）。
 *
 *＜p＞当返回类型为｛@codejava.util.concurrent.Foure｝时，抛出任何异常
 *在执行期间可以由调用者访问和管理。使用｛@code void｝
 *然而，这种异常不能被传回。在这种情况下
 *｛@link AsyncUnaughtExceptionHandler｝可以注册以处理此类异常。
 *
 *＜p＞注意：｛@code AnnotationSyncExecutionInterceptor｝子类是首选的
 *由于其与Spring的合作支持执行人资格
 *｛@code@Async｝注释。
 *
 *@作者Juergen Hoeller
 *@作者Chris Beams
 *@作者Stephane Nicoll
 *@自3.0
 *@参见org.springframework.scheduling.annotation.Async
 *@参见org.springframework.scheduling.annotation.AsyncAnnotationAdmin
 *@参见org.springframework.scheduling.annotation.AnnotationSyncExecutionInterceptor
 */
public class AsyncExecutionInterceptor extends AsyncExecutionAspectSupport implements MethodInterceptor, Ordered {

	/**
	 * Create a new instance with a default {@link AsyncUncaughtExceptionHandler}.
	 * @param defaultExecutor the {@link Executor} (typically a Spring {@link AsyncTaskExecutor}
	 * or {@link java.util.concurrent.ExecutorService}) to delegate to; a local
	 * executor for this interceptor will be built otherwise
	 */
	/**
	 *使用默认的｛@link AsyncUnaughtExceptionHandler｝创建一个新实例。
	 *@param defaultExecutor｛@link Executor｝（通常是Spring｛@linkAsyncTaskExecutor）
	 *或｛@linkjava.util.concurrent.ExecutorService｝）；本地人
	 *否则将生成此拦截器的执行器
	 */
	public AsyncExecutionInterceptor(@Nullable Executor defaultExecutor) {
		super(defaultExecutor);
	}

	/**
	 * Create a new {@code AsyncExecutionInterceptor}.
	 * @param defaultExecutor the {@link Executor} (typically a Spring {@link AsyncTaskExecutor}
	 * or {@link java.util.concurrent.ExecutorService}) to delegate to; a local
	 * executor for this interceptor will be built otherwise
	 * @param exceptionHandler the {@link AsyncUncaughtExceptionHandler} to use
	 */
	/**
	 *创建新的｛@code AsyncExecutionInterceptor｝。
	 *@param defaultExecutor｛@link Executor｝（通常是Spring｛@linkAsyncTaskExecutor）
	 *或｛@linkjava.util.concurrent.ExecutorService｝）；本地人
	 *否则将生成此拦截器的执行器
	 *@param exceptionHandler要使用的｛@link AsyncUnaughtExceptionHandler｝
	 */
	public AsyncExecutionInterceptor(@Nullable Executor defaultExecutor, AsyncUncaughtExceptionHandler exceptionHandler) {
		super(defaultExecutor, exceptionHandler);
	}


	/**
	 * Intercept the given method invocation, submit the actual calling of the method to
	 * the correct task executor and return immediately to the caller.
	 * @param invocation the method to intercept and make asynchronous
	 * @return {@link Future} if the original method returns {@code Future}; {@code null}
	 * otherwise.
	 */
	/**
	 *拦截给定的方法调用，将方法的实际调用提交给
	 *并立即返回给调用者。
	 *@param调用方法以拦截并使其异步
	 *如果原始方法返回｛@code Future｝，则返回｛@link Future｝；｛@code null｝
	 *否则。
	 */
	@Override
	@Nullable
	public Object invoke(final MethodInvocation invocation) throws Throwable {
		Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);
		Method specificMethod = ClassUtils.getMostSpecificMethod(invocation.getMethod(), targetClass);
		final Method userDeclaredMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);

		AsyncTaskExecutor executor = determineAsyncExecutor(userDeclaredMethod);
		if (executor == null) {
			throw new IllegalStateException(
					"No executor specified and no default executor set on AsyncExecutionInterceptor either");
		}

		Callable<Object> task = () -> {
			try {
				Object result = invocation.proceed();
				if (result instanceof Future<?> future) {
					return future.get();
				}
			}
			catch (ExecutionException ex) {
				handleError(ex.getCause(), userDeclaredMethod, invocation.getArguments());
			}
			catch (Throwable ex) {
				handleError(ex, userDeclaredMethod, invocation.getArguments());
			}
			return null;
		};

		return doSubmit(task, executor, invocation.getMethod().getReturnType());
	}

	/**
	 * Get the qualifier for a specific executor to use when executing the given
	 * method.
	 * <p>The default implementation of this method is effectively a no-op.
	 * <p>Subclasses may override this method to provide support for extracting
	 * qualifier information &mdash; for example, via an annotation on the given
	 * method.
	 * @return always {@code null}
	 * @since 3.1.2
	 * @see #determineAsyncExecutor(Method)
	 */
	/**
	 *获取特定执行器在执行给定的
	 *方法。
	 *＜p＞这个方法的默认实现实际上是一个no-op。
	 *＜p＞子类可以重写此方法，以支持提取
	 *限定符信息&mdash；例如，通过给定
	 *方法。
	 *@return always｛@code null｝
	 *@自3.1.2
	 *@参见#determineSyncExecutor（方法）
	 */
	@Override
	@Nullable
	protected String getExecutorQualifier(Method method) {
		return null;
	}

	/**
	 * This implementation searches for a unique {@link org.springframework.core.task.TaskExecutor}
	 * bean in the context, or for an {@link Executor} bean named "taskExecutor" otherwise.
	 * If neither of the two is resolvable (e.g. if no {@code BeanFactory} was configured at all),
	 * this implementation falls back to a newly created {@link SimpleAsyncTaskExecutor} instance
	 * for local use if no default could be found.
	 * @see #DEFAULT_TASK_EXECUTOR_BEAN_NAME
	 */
	/**
	 *此实现搜索唯一的｛@link.org.springframework.core.task.TaskExecutor｝
	 *bean，否则为名为“taskExecutor”的｛@link Executor｝bean。
	 *如果两者都不可解析（例如，如果根本没有配置{@code BeanFactory}），
	 *此实现返回到新创建的｛@link SimpleAsyncTaskExecutor｝实例
	 *如果找不到默认值，则供本地使用。
	 *@参见#DEFAULT_TASK_EXECUTOR_BEAN_NAME
	 */
	@Override
	@Nullable
	protected Executor getDefaultExecutor(@Nullable BeanFactory beanFactory) {
		Executor defaultExecutor = super.getDefaultExecutor(beanFactory);
		return (defaultExecutor != null ? defaultExecutor : new SimpleAsyncTaskExecutor());
	}

	@Override
	public int getOrder() {
		return Ordered.HIGHEST_PRECEDENCE;
	}

}
